package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController("userAddressController")
@Slf4j
@Api(tags = "地址接口")
@RequestMapping("/user/addressBook")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @GetMapping("/list")
    @ApiOperation("地址列表")
    public Result<List<AddressBook>> list() {
        Long userId = BaseContext.getCurrentId();//用户id
        List<AddressBook> addressBookList = addressService.list(userId);
        return Result.success(addressBookList);
    }

    @PostMapping
    @ApiOperation("新增地址")
    public Result addAddress(@RequestBody AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();//用户id
        addressBook.setUserId(userId);
        List<AddressBook> addressBookList = addressService.list(userId);
        //如果只有一个地址就是默认地址
        if (addressBookList.size() <= 0) {
            addressBook.setIsDefault(1);
        } else {
            addressBook.setIsDefault(0);
        }
        addressService.addAddress(addressBook);
        return Result.success();
    }

    @GetMapping("/default")
    @ApiOperation("查看默认地址")
    public Result findIsDefaul() {
        Long userId = BaseContext.getCurrentId();//用户id
        AddressBook defaultAddress = addressService.findIsDefault(userId);
        return Result.success(defaultAddress);
    }

    @PutMapping("/default")
    @ApiOperation("修改默认地址")
    public Result reviseAddressStatus(@RequestBody AddressBook addressBook) {
        //先将该用户的所有地址设置为非默认地址
        Long userId = BaseContext.getCurrentId();//用户id
        addressService.toNullDefaul(userId);
        // 更改该地址为默认地址
        Long id = addressBook.getId();
        addressService.toDefault(id);
        return Result.success();
    }

    @GetMapping("{id}")
    @ApiOperation("根据地址id查询地址")
    public Result<AddressBook> getAddressById(Long id) {
        AddressBook address = addressService.getAddressById(id);
        return Result.success(address);
    }

    @PutMapping
    @ApiOperation("修改地址")
    public Result updateAddress(@RequestBody AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();//用户id
        addressBook.setUserId(userId);
        addressService.updateAddress(addressBook);
        return Result.success();
    }

    @DeleteMapping
    @ApiOperation("删除地址")
    public Result deleteAddress(Long id){
        addressService.deleteAddress(id);
        return Result.success();
    }
}
